package cn.bytemecc.bloomFilter.service.save.impl;

import cn.bytemecc.bloomFilter.bitmap.DefaultBitmap;
import cn.bytemecc.bloomFilter.cache.SimpleCaffeine;
import cn.bytemecc.bloomFilter.service.save.ISaveCacheService;
import cn.bytemecc.bloomFilter.strategy.IHashGenerator;

import java.util.Objects;

/**
 * @description: TODO
 * @author: Liang Zi cao
 * @DATE: 2023/7/16
 * Talk is cheap. Show me the code
 **/
public class SaveCacheServiceImpl implements ISaveCacheService {

    private IHashGenerator hashGenerator;
    private SimpleCaffeine simpleCaffeine;

    public SaveCacheServiceImpl(IHashGenerator hashGenerator, SimpleCaffeine simpleCaffeine) {
        this.hashGenerator = hashGenerator;
        this.simpleCaffeine = simpleCaffeine;
    }

    @Override
    public boolean save(String bitMapKey, Object value) {
        DefaultBitmap bitMap = simpleCaffeine.getBitMap(bitMapKey);
        if (Objects.isNull(bitMap)){
            return false;
        }
        Integer hash = hashGenerator.doHash(value, bitMap.getSize());
        bitMap.setBit(hash);
        return true;
    }
}
